import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dio/dio.dart';

import '../services/UserInfo.dart';
import '../services/ScreenAdapter.dart';
import '../config/Config.dart';
import '../widget/MyButton.dart';
import '../services/SignServices.dart';
import '../services/EventBus.dart';

// provider
import 'package:provider/provider.dart';
import '../provider/CheckOut.dart';
import '../provider/Cart.dart';

// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

// 结算订单页面
class CheckOutPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => CheckOutState();
}

class CheckOutState extends State<CheckOutPage> {
  bool isLogin;
  var checkOutProvider;
  var cartProvider;
  Map addressInfo; // 默认收货地址信息
  var actionEvent;

  @override
  Widget build(BuildContext context) {
    final checkOutProvider = Provider.of<CheckOut>(context);
    final cartProvider = Provider.of<Cart>(context);
    this.checkOutProvider = checkOutProvider;
    this.cartProvider = cartProvider;

    return Scaffold(
      appBar: AppBar(title: Text('订单页面')),
      body: Stack(
        children: [
          ListView(
            children: [
              // 地址
              Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: ScreenAdapter.height(200),
                child: this.addressInfo == null
                    ? ListTile(
                        leading: Icon(Icons.add_location, size: 26),
                        title: Text('请添加您的收货地址', textAlign: TextAlign.center),
                        trailing: Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.pushNamed(context, '/addressList');
                        },
                      )
                    : ListTile(
                        title: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                                '${addressInfo['name']}  ${addressInfo['phone']}'),
                            Text('${addressInfo['address']}'),
                          ],
                        ),
                        trailing: Icon(Icons.keyboard_arrow_right),
                        onTap: () {
                          Navigator.pushNamed(context, '/addressList');
                        },
                      ),
              ),
              Divider(
                  thickness: ScreenAdapter.height(30),
                  color: Color.fromRGBO(200, 200, 200, 0.2)),

              // 商品列表
              Column(
                children: checkOutProvider.checkOutListData.map((cartItem) {
                  String pic = cartItem['pic'];
                  return Column(
                    children: [
                      Container(
                        width: double.infinity,
                        height: ScreenAdapter.height(200),
                        padding: EdgeInsets.all(10),
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: 10),
                              width: ScreenAdapter.width(160),
                              height: ScreenAdapter.height(160),
                              child: Image.network(
                                '${Config.domain + pic.replaceAll('\\', '/')}',
                                fit: BoxFit.fill,
                              ),
                            ),
                            Expanded(
                              flex: 1,
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('${cartItem['title']}',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(fontSize: 12)),
                                  Text('${cartItem['selectedAttr']}',
                                      style: TextStyle(fontSize: 12)),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('￥${cartItem['price']}',
                                          style: TextStyle(
                                              fontSize: 12, color: Colors.red)),
                                      Text('*${cartItem['count']}',
                                          style: TextStyle(
                                              fontSize: 12, color: Colors.red))
                                    ],
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                      cartItem ==
                              checkOutProvider.checkOutListData[
                                  checkOutProvider.checkOutListData.length - 1]
                          ? Container(height: 0)
                          : Divider(),
                    ],
                  );
                }).toList(),
              ),

              Divider(
                  thickness: ScreenAdapter.height(30),
                  color: Color.fromRGBO(200, 200, 200, 0.2)),

              // 优惠
              Container(
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                  width: ScreenAdapter.height(120),
                  color: Colors.white,
                ))),
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 10),
                    Text('商品总金额：￥18元'),
                    SizedBox(height: 30),
                    Text('立减：￥8元'),
                    SizedBox(height: 30),
                    Text('运费：￥0元')
                  ],
                ),
              )
            ],
          ),

          // 底部固定定位付款、下单
          Positioned(
            bottom: 0,
            child: Container(
              width: ScreenAdapter.width(750),
              height: ScreenAdapter.height(100),
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(top: BorderSide(color: Colors.black12))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text('实付款：'),
                      Text('￥${checkOutProvider.allPrice}元',
                          style: TextStyle(
                            color: Colors.red,
                          ))
                    ],
                  ),
                  MyButton(
                    text: '立即下单',
                    color: Colors.red,
                    borderRadius: 2,
                    leftPadding: 25,
                    rightPadding: 25,
                    cb: _goCheckOut,
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  initState() {
    super.initState();

    // 获取用户默认收货地址
    _getOneAddress();

    // 监听默认地址改变
    this.actionEvent = eventBus.on<CheckOutAddressUploadEvent>().listen((event){
      // 获取用户默认收货地址
      _getOneAddress();
    });
  }

  dispose(){
    super.dispose();
    this.actionEvent.cancel();
  }

  // 去结算
  _goCheckOut() async {
    if (this.addressInfo != null){
      var userInfo = await UserInfoServices.getUserInfo();
      var tempJson = {
        "uid": userInfo[0]['_id'],
        "address": this.addressInfo['address'],
        "phone": this.addressInfo['phone'],
        "name": this.addressInfo['name'],
        "all_price": this.checkOutProvider.allPrice.toStringAsFixed(1),
        "products": json.encode(this.checkOutProvider.checkOutListData),
        "salt": userInfo[0]['salt'],
      };

      var sign = SignServices.getSign(tempJson);
      var api = Config.domain + 'api/doOrder';
      var response = await Dio().post(api, data: {
        "uid": userInfo[0]['_id'],
        "address": this.addressInfo['address'],
        "phone": this.addressInfo['phone'],
        "name": this.addressInfo['name'],
        "all_price": this.checkOutProvider.allPrice.toStringAsFixed(1),
        "products": json.encode(this.checkOutProvider.checkOutListData),
        "sign" : sign
      });
      var res = response.data;
      print(res);

      if(res['success']){

        // 将购物车中已下单商品删除，只渲染未选中下单的商品
        cartProvider.getCheckedFalseCartList();

        // 跳转到支付页面
        Navigator.pushNamed(context, '/pay');
      }else {
        // 弹框提示
        Fluttertoast.showToast(
          msg: "下单失败",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
      }
    }else {
      // 弹框提示
      Fluttertoast.showToast(
        msg: "请添加您的默认收货地址",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }

  }


  // 获取用户默认收货地址
  _getOneAddress() async {
    var userInfo = await UserInfoServices.getUserInfo();

    var tempJson = {
      "uid": userInfo[0]['_id'],
      "salt": userInfo[0]['salt'],
    };

    var sign = SignServices.getSign(tempJson);
    var api = Config.domain + 'api/oneAddressList';

    var response = await Dio().get(api, queryParameters: {
      "uid": userInfo[0]['_id'],
      "sign": sign,
    });

    var res = response.data;
    if (res['success']) {
      this.setState(() {
        if (res['result'].length > 0) {
          this.addressInfo = res['result'][0];
        }else {
          this.addressInfo = null;
        }
      });
    }
  }
}
